import { ExcelSheetData, TColumn, TDataRow } from '@/components/editable-excel-table';

// 辅助类型：提取列的数据索引
export type DataIndex<C extends TColumn> = C extends { dataIndex: string } ? C['dataIndex'] : never;

export type TableState<C extends TColumn = TColumn> = {
    sheetData: ExcelSheetData<C>;
    errorCount?: number;
    fixedErrorCount?: number; // 已修改的错误数量
    activeColumn?: DataIndex<C>;
    activeRow?: number;
    activeCell?: { rowIndex: number; dataIndex: DataIndex<C> };
    editingCell?: { rowIndex: number; dataIndex: DataIndex<C> };
    // 错误导航相关
    errorPositions: Array<{ rowIndex: number; columnIndex: number }>;
    currentErrorIndex: number;
    // 修改状态跟踪
    modifiedCells: Set<string>; // 格式: "rowIndex:dataIndex"
    // 初始数据备份
    initialData: TDataRow<C>[];
};

export type TableAction<C extends TColumn = TColumn> =
    | { type: 'SET_SHEET_DATA'; payload: ExcelSheetData<C> }
    | { type: 'SET_ERROR_COUNT'; payload: { totalErrors: number; fixedErrorCount: number } }
    | { type: 'SET_COLUMNS'; payload: (C & { width?: number })[] }
    | { type: 'SET_COLUMNS_WIDTH'; payload: { dataIndex: DataIndex<C>; width: number } }
    | { type: 'SET_DATA'; payload: TDataRow<C>[] }
    | { type: ''; payload?: DataIndex<C> }
    | { type: 'DELETE_ROW'; payload: number }
    | { type: 'UPDATE_CELL_VALUE'; payload: { rowIndex: number; dataIndex: DataIndex<C>; value: string } }
    | { type: 'NAVIGATE_TO_ERROR'; payload: 'next' | 'prev' }
    | { type: 'SET_ERROR_POSITIONS'; payload: Array<{ rowIndex: number; columnIndex: number }> }
    | {
          type: 'SET_ACTIVE_CELL';
          payload?: { rowIndex: number; dataIndex: DataIndex<C> };
      }
    | {
          type: 'SET_EDITING_CELL';
          payload?: { rowIndex: number; dataIndex: DataIndex<C> };
      }
    | {
          type: 'TRANSFORM_STATE';
          payload: (state: TableState<C>) => TableState<C>;
      };
